package com.kunya.product.service.impl.product;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.kunya.common.common.Const;
import com.kunya.common.common.ResponseCode;
import com.kunya.common.common.ServerResponse;
import com.kunya.common.exception.ServerException;
import com.kunya.common.util.CopyPropertiesUtil;
import com.kunya.common.util.PropertiesUtil;
import com.kunya.product.dao.category.CategoryMapper;
import com.kunya.product.dao.product.ProductMapper;
import com.kunya.product.po.*;
import com.kunya.product.service.category.ICategoryService;
import com.kunya.product.service.category.IProductCategoryService;
import com.kunya.product.service.product.*;
import com.kunya.product.service.specofocation.IProductSpecificationService;
import com.kunya.product.vo.ProductDetailVo;
import com.kunya.product.vo.ProductListVo;
import com.kunya.product.vo.ProductVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zp
 * @Description: 商品service实现类test
 * @date 2018/5/30 9:59
 */
@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ICategoryService iCategoryService;
    @Autowired
    private IProductCategoryService iProductCategoryService;
    @Autowired
    private IProductAtrributeService iProductAtrributeService;
    @Autowired
    private IProductDetailService iProductDetailService;
    @Autowired
    private IProductSpecificationService iProductSpecificationService;
    @Autowired
    private IProductImageService iProductImageService;
    @Autowired
    private IProductParameterService iProductParameterService;


    /**
     * @param productId
     * @author zp
     * @Description: 前台获取商品详情方法, os-product表数据
     * @date 2018/5/30 13:55
     */
    @Override
    public ServerResponse<ProductDetailVo> getProductDetailVo(Long productId, String tablePrefix) {
        if (productId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
        }
        Product product = productMapper.selectByPrimaryKey(productId, tablePrefix);
        if (product == null) {
            return ServerResponse.createByErrorMessage("产品已下架或者删除");
        }
        //前台查看商品详情只能查看上架的产品        是否根据 showInShelve 判断商品上架？
        if (product.getShowInShelve() != Const.ProductStatusEnum.ON_SALE.getCode()) {
            return ServerResponse.createByErrorMessage("产品已下架或者删除");
        }
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }

    /**
     * @param
     * @author zp
     * @Description: 用于将商品po组装为商品详情vo
     * @date 2018/5/30 13:56
     */
    private ProductDetailVo assembleProductDetailVo(Product product) {
        ProductDetailVo productDetailVo = new ProductDetailVo();
        BeanUtils.copyProperties(product,productDetailVo);
        productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        return productDetailVo;
    }

    /**
     * @param keyword：关键词模糊查询
     * @param categoryId:分类id
     * @param pageNum:分页页码，
     * @param pageSize：分页长度
     * @param orderBy：排序      与前端约定 以哪个字段排序-升序或降序  “-”英文半角此符号分隔
     * @author zp
     * @Description: 根据分类或关键词查询商品列表
     * @date 2018/6/1 11:15
     */
    @Override
    public ServerResponse<PageInfo> getProductByKeywordCategory(String keyword, Long categoryId,
                                                                int pageNum, int pageSize, String orderBy, String tablePrefix) {
        //判断参数是否都为空
        if (StringUtils.isBlank(keyword) && categoryId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "搜索商品参数错误");
        }
        List<Long> categoryIdList = new ArrayList<Long>();
        //前端传了categoryId
        if (categoryId != null) {
            Category category = categoryMapper.selectByPrimaryKey(categoryId, tablePrefix);
            //如果数据库中不存在该分类
            if (category == null && StringUtils.isBlank(keyword)) {
                //没有该分类返回一个空结果集
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVo> productListVoList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(productListVoList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            //如果categoryId不为空拿出所有子分类
            categoryIdList = iCategoryService.selectCategoryAndChildrenById(categoryId, tablePrefix).getData();
        }
        PageHelper.startPage(pageNum, pageSize);
        //拼接keyword
        //与前端约定 以哪个字段排序-升序或降序  “-”英文半角此符号分隔
        if (StringUtils.isNoneBlank(keyword)) {
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
            //动态排序
            if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
                String[] orderArray = orderBy.split("_");
                PageHelper.orderBy(orderArray[0] + " " + orderArray[1]);
            }
        }
        //根据分类id list 从os_product_category表获取商品id list
        List<Long> productIdList = Lists.newArrayList();
        ServerResponse<List<Long>> serverResponse = iProductCategoryService.getProductIdListByCategoryIds(categoryIdList, tablePrefix);
        if (serverResponse.isSuccess()) {
            productIdList = serverResponse.getData();
        }
        //根据分类id 查询商品列表
        List<Product> productList = productMapper.selectByProductNameAndIds(StringUtils.isBlank(keyword) ? null : keyword, productIdList.size() == 0 ? null : productIdList, tablePrefix);
        List<ProductListVo>  productVoList = Lists.newArrayList();
        for (Product product : productList) {
            ProductListVo productListVo = assembleProductListVo(product);
            productVoList.add(productListVo);
        }
        PageInfo pageInfo = new PageInfo(productVoList);

        return ServerResponse.createBySuccess(pageInfo);
    }

    //将product对象转化为list使用的vo对象
    private ProductListVo assembleProductListVo(Product product) {
        ProductListVo productListVo = new ProductListVo();
        BeanUtils.copyProperties(product,productListVo);
//        productListVo.setCategoryId(product.getCategoryId());
        //图片主机地址从配置文件中读取，不存数据库，为了迁移灵活
        productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        return productListVo;
    }

    /**
     * @param
     * @author zp
     * @Description: 新增商品
     * @date 2018/6/16 18:11
     */
    @Override
    @Transactional
    public ServerResponse saveProduct(Long[] categoryIds, Product product, String tablePrefix) {
        if (categoryIds == null || product == null || categoryIds.length == 0||StringUtils.isEmpty(tablePrefix)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
//        product.setProductNumber(CommonUtil.getNumber());
        //1.向商品表插入数据
        int resultCount = productMapper.insertSelective(product, tablePrefix);
        if (resultCount <= 0) {
            throw new RuntimeException("插入商品失败");
        }
        Long productId = product.getProductId();//获取插入product表时自增返回的主键
        //2.向商品分类表插入数据 list
        List<ProductCategory> productCategoryList = Lists.newArrayList();
        for (int i = 0; i < categoryIds.length; i++) {
            ProductCategory productCategory = new ProductCategory();
            productCategory.setCategoryId(categoryIds[i]);
            productCategory.setProductId(productId);
            productCategory.setCreateTime(null);
            productCategory.setCreateBy(null);
            productCategoryList.add(productCategory);
        }
        iProductCategoryService.saveProductCategorys(productCategoryList, tablePrefix);

        //3.插入商品属性表
        ProductAttribute productAttribute = assembleProductAttributePo(productId);
        ServerResponse attrServerResponse = iProductAtrributeService.saveProductAttribute(productAttribute, tablePrefix);
        if (!attrServerResponse.isSuccess()) {
            throw new RuntimeException("插入商品属性失败");
        }
        //4.插入商品描述表 productdetail
        ProductDetail productDetail = assembleProductDetail(productId);
        ServerResponse detailServerResponse=iProductDetailService.savaProductDetail(productDetail,tablePrefix);
        if(!attrServerResponse.isSuccess()){
            throw new RuntimeException("插入商品图文详情失败");
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    @Transactional
    public ServerResponse removeProduct(Long productId, String tablePerfix) throws IOException {
        if (productId == null ||StringUtils.isEmpty(tablePerfix)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        ServerResponse[] responses=new ServerResponse[7];

        //1.删除主表信息
        responses[0]=productMapper.deleteByPrimaryKey(productId,tablePerfix)==1?
                ServerResponse.createBySuccess("删除商品主表成功"):ServerResponse.createByErrorMessage("商品ID不存在");

        //2.删除商品规格信息
        responses[1]=iProductSpecificationService.deleteProductSpecificationByProductId(productId,tablePerfix);

        //3.删除商品分类信息
        responses[2]=iProductCategoryService.deleteProductCategorysByProductId(productId,tablePerfix);

        //4.删除商品属性信息
        responses[3]=iProductAtrributeService.deleteProductAttributeByProductId(productId,tablePerfix);

        //5.删除商品详情
        responses[4]=iProductDetailService.deleteProductDetailByProductId(productId,tablePerfix);

        //6.删除商品图片
        responses[5]=iProductImageService.deleteProductImageByProductId(productId,tablePerfix);

        //7.删除商品参数
        responses[6]=iProductParameterService.deleteProductParameterByProductId(productId,tablePerfix);

        //检查删除结果,如果有一个删除失败 抛出异常 事务回滚
        for (ServerResponse response: responses) {
            if(response!=null&&!response.isSuccess()){
                throw new ServerException("删除商品失败,因为:"+response.getMsg());
            }
        }

        return ServerResponse.createBySuccess("删除商品成功");
    }

    @Override
    public ServerResponse offlineProduct(Long productId, String tablePerfix) {
        if(null==productId||StringUtils.isBlank(tablePerfix)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product=new Product();
        product.setProductId(productId);
        product.setShowInShelve((byte)0);
        return productMapper.updateByPrimaryKeySelective(product,tablePerfix)==1?
                ServerResponse.createBySuccess("下架商品成功"):ServerResponse.createByErrorMessage("下架商品失败");
    }

    @Override
    @Transactional
    public ServerResponse updateProduct(ProductVo productVo,String tablePerfix) {
        Product product = new Product();
        //1.不复制空的属性2.忽略指定属性
        CopyPropertiesUtil.copyPropertiesIgnoreNull(productVo,product,"updateTime","updateBy","createTime","createBy");
        product.setUpdateTime(new Date());
        //TODO 从Shrio当中获取当前用户名
        product.setUpdateBy("Suimg");
        productMapper.updateByPrimaryKeySelective(product,tablePerfix);
        if(productVo.getCategoryIds()!=null){
            ProductCategory productCategory=new ProductCategory();
            //CopyPropertiesUtil.copyPropertiesIgnoreNull(productVo,productCategory);
            ServerResponse response;
            if(!(response=iProductCategoryService.updateProductCategorys(productVo.getProductId(),productVo.getCategoryIds(), tablePerfix)).isSuccess()){
                return ServerResponse.createByErrorMessage("修改商品失败!因为:"+response.getMsg());
            }
        }
        return ServerResponse.createBySuccess("修改商品成功");
    }

    /**
     * @param
     * @author zp
     * @Description: 组装ProductAttributePo
     * @date 2018/7/2 1 3:39
     */
    private ProductAttribute assembleProductAttributePo(Long productId) {

        ProductAttribute productAttribute = new ProductAttribute();
        productAttribute.setProductId(productId);
        productAttribute.setStock(0);//初始设置总库存为0
        productAttribute.setSalesVolume(0);//初始设置总销量0
        productAttribute.setPageViews(0);//初始设置总浏览量0
        productAttribute.setCommentNumber(0);//初始设置总评论数量0
        productAttribute.setCommentTotal(0);//初始设置累计评价0
        productAttribute.setCommentAverage(0L);//初始设置平均评价0
        productAttribute.setFavoriteNumber(0);//初始设置收藏数0
        productAttribute.setQuestionNumber(0);//初始设置提问数0

        return productAttribute;
    }

    /**
     * @param
     * @author zp
     * @Description: 组装ProductDetail
     * @date 2018/7/3 13:35
     */
    private ProductDetail assembleProductDetail(Long productId) {
        ProductDetail productDetail = new ProductDetail();
        productDetail.setProductId(productId);
        return productDetail;

    }

}
